<template>
  <div class="hazardChemicalManage">
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.chemicalmanage_delete" @click="handleDelete">删 除</el-button>
          <el-button type="success" size="small" icon="el-icon-upload2" plain v-if="permission.chemicalmanage_import" @click="handleImport">导 入</el-button>
          <el-button type="warning" size="small" icon="el-icon-download" plain v-if="permission.chemicalmanage_export" @click="handleExport">导 出</el-button>
        </template>

        <!-- 危险化学品名称和说明下拉框可选可输自定义 -->
        <template slot-scope="scope" slot="wxhxpmchsmForm">
          <el-select v-model="form.wxhxpmchsm" filterable placeholder="请选择" @blur="searchBlur">
            <el-option
              v-for="item in whpmcList"
              :key="item.dictValue"
              :label="item.dictKey"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </template>

      </avue-crud>

      <!-- 导入弹窗-->
      <el-dialog title="危化品信息管理" append-to-body :visible.sync="excelBox" width="555px">
        <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
  import {getList, getDetail, add, update, remove, getWxhxpmchsm, getBmCASHLjlLinkInfo, getWxxfljsmLjlLinkInfo} from "@/api/mmhi/chemicalmanage";
  import {validateDigitOrPoint, validateIsPositive} from "@/api/mmhi/validate";
  import {mapGetters} from "vuex";
  import {getToken} from "@/util/auth";

  export default {
    data() {
      return {
        form: {},
        query: {},
        excelBox: false,
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '模板上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              loadText: '模板上传中，请稍等',
              showFileList: false,
              span: 24,
              propsHttp: {
                res: 'data'
              },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: "/api/hazardChemicalManage/chemicalmanage/import-chemicalManage"
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24
            }
          ]
        },
        option: {
          height:'auto',
          refreshBtn: true,
          columnBtn: true,
          calcHeight: 30,
          dialogWidth: 950,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "危险化学品名称和说明",
              prop: "wxhxpmchsm",
              width: "145px",
              align: "center",
              search: true,
              filterable: true,
              formslot: true,
              rules: [{
                required: true,
                message: "请输入危险化学品名称和说明",
                trigger: "blur"
              }],
            },
            {
              label: "别名",
              prop: "bm",
              align: "center",
              maxlength:32,
              rules: [{
                required: false,
                message: "请输入别名",
                trigger: "blur"
              }]
            },
            {
              label: "CAS号",
              prop: "cash",
              align: "center",
              maxlength:32,
              rules: [{
                required: false,
                message: "请输入CAS号",
                trigger: "blur"
              }]
            },
            {
              label: '类别',
              prop: 'lb',
              align: "center",
              type: 'tree',
              search: true,
              dataType: "number",
              cascaderIndex:0,
              props: {
                label: 'dictValue',
                value: 'dictKey'
              },
              cascaderItem: ['fh'],
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=hazardChemical_lb",
              rules: [{
                required: true,
                message: "请选择类别",
                trigger: "blur"
              }]
            },
            {
              label: '符号',
              prop: 'fh',
              align: "center",
              type: 'tree',
              multiple: true,
              cascaderIndex:0,
              props: {
                label: 'dictValue',
                value: 'dictKey'
              },
              dicFlag: false,
              dicUrl: "/api/hazardChemicalManage/chemicalmanage/getFh?lbBm={{key}}",
              rules: [{
                required: true,
                message: "请选择符号",
                trigger: "blur"
              }]
            },
            {
              label: "危险性分类及说明",
              width: "130px",
              prop: "wxxfljsm",
              align: "center",
              disabled: true
            },
            {
              label: "临界量/t",
              prop: "ljl",
              align: "center",
              disabled: true,
              rules: [{
                required: true,
                message: "请输入临界量/t",
                trigger: "blur"
              }]
            },
            {
              label: "危险化学品实际存在量/t",
              prop: "sjczl",
              align: "center",
              maxlength:16,
              hide: true,
              rules: [{
                required: true,
                validator: validateDigitOrPoint,
                trigger: "blur"
              }]
            },
            {
              label: "厂外可能暴露人员数量",
              prop: "cqwblry",
              align: "center",
              maxlength:10,
              hide: true,
              rules: [{
                required: true,
                validator: validateIsPositive,
                trigger: "blur"
              }]
            },
            {
              label: "是否为重大危险源",
              width: "130px",
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=hazardChemical_sfwzdwxy",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              prop: "sfwzdwxy",
              search: true,
              align: "center",
              dataType: "number",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "重大危险源名称",
              width: "130px",
              prop: "zdwxymc",
              align: "center",
              maxlength:32,
              rules: [{
                required: true,
                message: "请输入重大危险源名称",
                trigger: "blur"
              }]
            },
            {
              label: "重大危险源等级",
              width: "130px",
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=hazardChemical_zdwxydj",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              prop: "zdwxydj",
              align: "center",
              dataType: "number",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "R值",
              prop: "rz",
              align: "center",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "企业id",
              prop: "bladeDeptId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "租户id",
              prop: "tenantId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建人",
              prop: "createUser",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建部门",
              prop: "createDept",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建时间",
              prop: "createTime",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "自定义巡检点id",
              prop: "patrolPointCustomSettingsId",
              align: "center",
              row: false,
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
            }
          ]
        },
        data: [],

        //危险化学品名称和说明
        whpmcList: [],

        //临界量
        ljlArea:""
      };
    },
    mounted() {
      this.initData();
    },
    watch: {
      'form.wxhxpmchsm':{
        handler(val){
          if(val!='' && val!=undefined && val!=null){
            getBmCASHLjlLinkInfo(val).then(res=>{
              this.form.bm = res.data.data[0].bm;
              this.form.cash = res.data.data[0].cash;
              this.form.ljl = res.data.data[0].ljl;
            });
          }
        },
        immediate: true
      },
      'form.fh':{
        handler(val){
          if(val!='' && val!=undefined && val!=null){
            getWxxfljsmLjlLinkInfo(val).then(res=>{
              this.ljlArea ="";
              this.ljlArea = res.data.data[0].ljl;
              this.form.wxxfljsm = res.data.data[0].wxxfljsm;
            }).then(() => {
              getBmCASHLjlLinkInfo(this.form.wxhxpmchsm).then(res=>{
                if(res.data.data[0].ljl==""){
                  this.form.ljl = this.ljlArea ;
                }
              });
            });
          }else{
            this.form.wxxfljsm = "";
            getBmCASHLjlLinkInfo(this.form.wxhxpmchsm).then(res=>{
              if(res.data.data[0].ljl==""){
                this.form.ljl = "";
              }
            });
          }
        },
        immediate: true
      }
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.chemicalmanage_add, false),
          viewBtn: this.vaildData(this.permission.chemicalmanage_view, false),
          delBtn: this.vaildData(this.permission.chemicalmanage_delete, false),
          editBtn: this.vaildData(this.permission.chemicalmanage_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      // 初始化数据
      initData() {
        this.getWxhxpmchsmList();
      },

      getWxhxpmchsmList() {
        this.whpmcList = []
        getWxhxpmchsm().then(res => {
          this.whpmcList = res.data.data;
        })
      },

      searchBlur(e) {
        this.form.wxhxpmchsm = e.target.value.slice(0,32);
      },

      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },

      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },

      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },

      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },

      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },

      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },

      handleImport() {
        this.excelBox = true;
      },
      uploadAfter(res, done, loading, column) {
        window.console.log(column);
        this.excelBox = false;
        this.refreshChange();
        done();
      },

      handleTemplate() {
        window.open(`/api/hazardChemicalManage/chemicalmanage/export-template?${this.website.tokenHeader}=${getToken()}`);
      },

      handleExport() {
        this.$confirm("是否导出危化品管理信息?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api/hazardChemicalManage/chemicalmanage/export-chemicalManage?${this.website.tokenHeader}=${getToken()}`);
        });
      }
    }
  };
</script>

<style lang="scss">
  .hazardChemicalManage {
    .el-form-item__label {
      width: 160px !important;
    }

    .avue-form__row {
      .el-form-item__content {
        margin-left: 160px !important;
      }
    }
  }

</style>

<style lang="scss" scpoed>
  .avue-crud__dialog {
    .el-dialog__body {
      .el-form-item__label {
        width: 95px !important;
      }

      .avue-form__row {
        .el-form-item__content {
          margin-left: 95px !important;
        }
      }
    }
  }

  .el-dialog__wrapper {
    .el-dialog__body {
      padding: 10px 20px 20px 20px;

      .el-form-item__label {
        width: 72px;
      }

      .avue-form__row {
        .el-form-item__content {
          margin-left: 72px;
        }
      }

      .avue-crud__menu {
        display: none;
      }
    }
  }
</style>
